package com.haiheng.module_main.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.Keys
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.toast.AppUtils
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.toast.Utils
import com.haiheng.library_base.utils.ApplicationUtils
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.library_base.utils.SystemUtil
import com.haiheng.library_base.view.webview.JSInterface
import com.haiheng.module_main.R
import com.haiheng.module_main.databinding.SettingFragment1Binding
import com.haiheng.module_main.databinding.SettingFragmentBinding
import com.haiheng.module_main.mode.SettingViewModel
import com.haiheng.videodoorbell.widget.webview.IX5WebPageView
import com.haiheng.videodoorbell.widget.webview.MyX5WebChromeClient
import com.haiheng.videodoorbell.widget.webview.MyX5WebViewClient
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.WebView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/12/15 0015
 * @Version: 1.0
 */
class SettingFragment:RouterFragment() , IX5WebPageView {
    private lateinit var binding: SettingFragmentBinding
    private val settingViewModel: SettingViewModel by viewModels()
    private val TAG: String = "SettingFragment"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = SettingFragmentBinding.inflate(inflater,container,false)

        LogUtils.e(TAG+"onCreateView")
        return binding!!.root
    }
    override fun initView() {
        LogUtils.e(TAG+"initView")
        binding.includeConfig.etUrl.setText(AppConstant.getWebViewUrl())
        binding.includeConfig.etBaseUrl.setText(API.getBaseUrl())
        binding.includeConfig.etLibraryCode.setText(AppConstant.getLibraryCode())
        binding.includeConfig.etWebSite.setText(AppConstant.getWebpageSize().toString())
        binding.includeConfig.etPageCounDownTime.setText(AppConstant.getPageCountDownTime().toString())
        binding.includeConfig.etMachineName.setText(AppConstant.getMachineName().toString())
        binding.includeConfig.etMachineCatalogType.setText(AppConstant.getMachineCatalogType().toString())
        binding.includeConfig.etMachineModelType.setText(AppConstant.getMachineModelType().toString())
        binding.includeConfig.etReportInterval.setText(AppConstant.getReportInterval().toString())
        binding.includeConfig.etAcsUrl.setText(API.getAcsUrl().toString())
        binding.includeConfig.switchOpenFace.isChecked = AppConstant.isOpenFace()
        binding.includeConfig.switchLog.isChecked = AppConstant.isOpenLog()
        binding.includeConfig.switchVoice.isChecked = AppConstant.isOpenNoiseReduction()
        binding.includeConfig.switchUseAiui.isChecked = AppConstant.isUseAIUI()
        binding.includeConfig.switchUseOfflineVoice.isChecked = AppConstant.isOpenOfflineVoice()
        binding.includeConfig.switchShowBackBtn.isChecked = AppConstant.isShowBackBtn()
        binding.includeConfig.switchPatronPasswordValid.isChecked = AppConstant.isPatronPasswordValid()
        binding.includeConfig.switchOpenDebugView.isChecked = AppConstant.isOpenView()
        binding.includeConfig.switchExitApp.isChecked = AppConstant.isExitOpenApp()
        binding.includeConfig.etMqttUrl.setText(AppConstant.getBrokerUrl().toString())
        binding.includeConfig.etMqttName.setText(AppConstant.getMqttName().toString())
        binding.includeConfig.etMqttPassword.setText(AppConstant.getMqttPassword().toString())
        //人脸
        binding.includeConfig.etFaceBaseUrl.setText(API.getFaceUrl())
        binding.includeConfig.etFaceLibraryCode.setText(AppConstant.getFaceLibraryCode())
        binding.includeConfig.etFaceAccount.setText(AppConstant.getFaceTokenAccount())
        binding.includeConfig.etFacePassword.setText(AppConstant.getFacePassword())

        initPortName()
        initBoardVersion()
        binding.includeConfig.tvVersion.setText("VersionName:${SystemUtil.getVersionName()}  " +
                    "VersionCode:${SystemUtil.getVersionCode()} lastRecordid:${AppConstant.getLastFaceResRecordId()}")
        binding.includeConfig.switchOpenDebugView.setOnClickListener {
            binding.includeConfig.switchOpenDebugView.isChecked =!AppConstant.isOpenView()
            SPUtils.getInstance().put(Keys.SWITCH_DEBUG_VIEW,binding.includeConfig.switchOpenDebugView.isChecked)
        }
        binding.includeConfig.switchExitApp.setOnClickListener {
            binding.includeConfig.switchExitApp.isChecked =!AppConstant.isExitOpenApp()
            SPUtils.getInstance().put(Keys.SWITCH_EXIT_OPEN_APP,binding.includeConfig.switchExitApp.isChecked)
        }
        binding.includeConfig.switchLog.setOnClickListener {
            binding.includeConfig.switchLog.isChecked =!AppConstant.isOpenLog()
            SPUtils.getInstance().put(Keys.SWITCH_OPEN_LOG,binding.includeConfig.switchLog.isChecked)
            LogWriter.setWriteFlag(AppConstant.isOpenLog())
        }
        binding.includeConfig.switchVoice.setOnClickListener{
            binding.includeConfig.switchVoice.isChecked =!AppConstant.isOpenNoiseReduction()
            SPUtils.getInstance().put(Keys.SWITCH_OPEN_NOISE_REDUCTION,binding.includeConfig.switchVoice.isChecked)
        }
        binding.includeConfig.switchUseAiui.setOnClickListener{
            binding.includeConfig.switchUseAiui.isChecked =!AppConstant.isUseAIUI()
            SPUtils.getInstance().put(Keys.SWITCH_USE_AIUI,binding.includeConfig.switchUseAiui.isChecked)
        }
        binding.includeConfig.switchUseOfflineVoice.setOnClickListener{
            binding.includeConfig.switchUseOfflineVoice.isChecked =!AppConstant.isOpenOfflineVoice()
            SPUtils.getInstance().put(Keys.SWITCH_OPEN_OFFLINE_VOICE,binding.includeConfig.switchUseOfflineVoice.isChecked)
        }
        binding.includeConfig.switchShowBackBtn.setOnClickListener{
            binding.includeConfig.switchShowBackBtn.isChecked =!AppConstant.isShowBackBtn()
            SPUtils.getInstance().put(Keys.SP_SHOW_BACK_BUTTON,binding.includeConfig.switchShowBackBtn.isChecked)
        }
        binding.includeConfig.switchPatronPasswordValid.setOnClickListener{
            binding.includeConfig.switchPatronPasswordValid.isChecked =!AppConstant.isPatronPasswordValid()
            SPUtils.getInstance().put(AppConstant.SP_IS_PATRON_PASSWORD_VALID,binding.includeConfig.switchPatronPasswordValid.isChecked)
        }
        binding.includeConfig.switchOpenFace.setOnClickListener {
            binding.includeConfig.switchOpenFace.isChecked = !AppConstant.isOpenFace()
            SPUtils.getInstance().put(AppConstant.SP_OPEN_FACE, binding.includeConfig.switchOpenFace.isChecked)
        }
        binding.includeConfig.btFaceSyc.setOnClickListener {
            settingViewModel.synFaceDate()
        }
        binding.includeConfig.btDelecFaceSycRecord.setOnClickListener {

        }
        binding.includeConfig.btnTestScan.setOnClickListener {

        }
        binding.llSave.setOnClickListener {
            var url = binding.includeConfig.etUrl.text.toString()
            var baseUrl = binding.includeConfig.etBaseUrl.text.toString()
            var libraryCode = binding.includeConfig.etLibraryCode.text.toString()
            var machineName = binding.includeConfig.etMachineName.text.toString()
            var reportInterVal = binding.includeConfig.etReportInterval.text.toString()
            var acsUrl = binding.includeConfig.etAcsUrl.text.toString()
            if (url.isNotBlank()){
                SPUtils.getInstance().put(AppConstant.SP_WEB_VIEW_URL,url)
            } else{
                ToastUtils.showShort("网页链接不能为空")
                return@setOnClickListener
            }

            if (baseUrl.isNotBlank()){
                SPUtils.getInstance().put(API.SP_BASE_URL,baseUrl)
            }else{
                ToastUtils.showShort("上报地址不能为空")
                return@setOnClickListener
            }
            if (libraryCode.isNotBlank()){
                SPUtils.getInstance().put(AppConstant.SP_LIBRARYCODE,libraryCode)
            }
            if (machineName.isNotBlank()) {
                SPUtils.getInstance().put(AppConstant.SP_MACHINE_NAME,machineName)
            }

            var webSize = binding.includeConfig.etWebSite.text.toString()
            if (webSize.isNotBlank()){
                SPUtils.getInstance().put(AppConstant.SP_WEBVIEW_SIZE,webSize.toInt())
            }
            var countDownTimer = binding.includeConfig.etPageCounDownTime.text.toString()
            if (countDownTimer.isNotBlank()){
                SPUtils.getInstance().put(AppConstant.SP_PAGE_COUNTDWN_TIME,countDownTimer.toInt())
            }
            if (reportInterVal.isNotBlank()){
                SPUtils.getInstance().put(AppConstant.SP_REPORT_INTERVAL,reportInterVal.toInt())
            }
            //mqtt
            SPUtils.getInstance().put(AppConstant.SP_MQTT_URL,binding.includeConfig.etMqttUrl.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_MQTT_NAME,binding.includeConfig.etMqttName.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_MQTT_PASSWORD,binding.includeConfig.etMqttPassword.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_MACHINE_CATALOG_TYPE,binding.includeConfig.etMachineCatalogType.text.toString().toInt())
            SPUtils.getInstance().put(AppConstant.SP_MACHINE_MODEL_TYPE,binding.includeConfig.etMachineModelType.text.toString())
            //人脸
            SPUtils.getInstance().put(AppConstant.SP_FACE_BASE_URL,binding.includeConfig.etFaceBaseUrl.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_FACE_LIBRARY_CODE,binding.includeConfig.etFaceLibraryCode.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_FACE_TOKEN_ACCOUNT,binding.includeConfig.etFaceAccount.text.toString())
            SPUtils.getInstance().put(AppConstant.SP_FACE_TOKEN_PASSWORD,binding.includeConfig.etFacePassword.text.toString())
            SPUtils.getInstance().put(API.SP_ACS_URL,acsUrl)
            ToastUtils.showShort("保存成功，退出程序，重新启动后生效")
        }
        binding.llExt.setOnClickListener {
            activity.finish()
//            Process.killProcess(Process.myPid())
            System.exit(0)
        }
        binding.llBack.setOnClickListener {
            activity.onBackPressed()
        }

        binding.includeConfig.btnTestUrl.setOnClickListener {
            binding.includeConfig.webview.visibility = View.VISIBLE
            initX5()
            binding.includeConfig.webview.loadUrl("http://debugtbs.qq.com")
        }

        binding.includeConfig.btnTestFace.setOnClickListener {
//            var intent = Intent(activity, StartActivity::class.java)
//            startActivity(intent)
        }

    }

    override fun initViewModel(): BaseViewModel? {
       settingViewModel.isSynFaceFinish.observe(viewLifecycleOwner) {
            if (it) {
                binding.includeConfig.tvTestInfo.setText("已同步至最新数据，暂无同步内容")
            }
        }
       return settingViewModel
    }

    override fun initLoad() {
        if (AppConstant.isOpenFace()){
        }

    }

    fun testLog(){

    }

   fun initX5(){
        LogUtils.e("initX5")


        //（可选）为了提高内核占比，在初始化前可配置允许移动网络下载内核（大小 40-50 MB）。默认移动网络不下载
        QbSdk.setDownloadWithoutWifi(true);
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        val cb: QbSdk.PreInitCallback = object : QbSdk.PreInitCallback {
            override fun onViewInitFinished(arg0: Boolean) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.e("webview  x5內核初始化:  $arg0")
                ToastUtils.showShort("内核初始化结果：$arg0")
            }

            override fun onCoreInitFinished() {
                LogUtils.e("webview  onCoreInitFinished")
            }
        }
        //x5内核初始化接口
        QbSdk.initX5Environment(ApplicationUtils.application, cb)
        // 在调用TBS初始化、创建WebView之前进行如下配置
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)

        binding.includeConfig.webview.webViewClient = MyX5WebViewClient(this)
        binding.includeConfig.webview.webChromeClient = MyX5WebChromeClient(this)
        binding.includeConfig.webview.addJavascriptInterface(JSInterface(this),"JsToCallAppFunc")
    }

    private fun initBoardVersion(){//初始化主板版本
//        var sysBoard = AppConstant.getSystemBoard()
//        val versionNames = resources.getStringArray(R.array.arr_borad_name).asList()
//        val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, versionNames)
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
//        binding.includeConfig.spinnerBoard.adapter = adapter
//        binding.includeConfig.spinnerBoard.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener{
//            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
//                var sysVerCode = versionNames.get(position)
//                LogUtils.d("选择对应系统主板版本：${sysVerCode}")
//                SPUtils.getInstance().put(AppConstant.SP_SYSTEM_VERSION_CODE,sysVerCode)
//            }
//
//            override fun onNothingSelected(parent: AdapterView<*>?) {
//
//
//            }
//        })
//        for (item in versionNames){
//            var index = versionNames.indexOf(item)
//            if (item.equals(sysBoard)){
//                binding.includeConfig.spinnerBoard.setSelection(index,true)
//            }
//        }
    }
    private fun initPortName() {
      /* var port = AppConstant.getCardSerialPortName()
        val arrPortName = resources.getStringArray(R.array.arr_port_name).asList()
        val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrPortName)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.includeConfig.spinnerPortName.adapter = adapter
        binding.includeConfig.spinnerPortName.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                var portName = arrPortName.get(position)
                LogUtils.d("选择端口：${portName}")
                SPUtils.getInstance().put(AppConstant.SP_SERIAL_PORNAME,portName)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {


            }
        })
        for (item in arrPortName){
            var index = arrPortName.indexOf(item)
            if (item.equals(port)){
                binding.includeConfig.spinnerPortName.setSelection(index,true)
            }
        }*/
    }
    override fun showWebView() {
        TODO("Not yet implemented")
    }

    override fun hindWebView() {

    }

    override fun startProgress(newProgress: Int) {
    }

    override fun startFileChooserForResult(intent: Intent?, requestCode: Int) {
    }

    override fun onPageFinished(view: WebView?, url: String?) {

        binding.includeConfig.webview.setInitialScale(AppConstant.getWebpageSize())

    }

    override fun isOpenThirdApp(url: String?): Boolean {
        if (url!!.startsWith("http")) {
            binding.includeConfig.webview.loadUrl(url)
        }
        return true
    }

    override fun onJsFunctionCalled(funName: String, key: String?, values: String?) {

    }

}